package lab.anoper.juc.automatic;

import sun.misc.Unsafe;

import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 闫家洪（yanjiahong@vcredit.com）
 * @since 2024/12/12
 */
public class MyAtomicInteger2 {
    private int value;
    private static final VarHandle VALUE_HANDLE;

    public MyAtomicInteger2(int value) {
        this.value = value;
    }

    static {
        try {
            VALUE_HANDLE = MethodHandles.lookup().findVarHandle(MyAtomicInteger2.class, "value", int.class);
        } catch (Exception e) {
            throw new Error(e);
        }
    }

    public int get() {
        return (int) VALUE_HANDLE.getVolatile(this);
    }

    public int incrementAndGet() {
        for (;;) {
            int currentValue = get();
            if (VALUE_HANDLE.compareAndSet(this, currentValue, currentValue + 1)) {
                return currentValue + 1;
            }
        }
    }
}
